<script setup lang="ts">
import { onMounted } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Card, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { genConfigAddOrEditApi, genConfigQueryOneApi } from '#/api/gen/config';
import { queryDictOptionsApi } from '#/utils';

const [OtherForm, otherFormApi] = useVbenForm({
  wrapperClass: 'grid-cols-2',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: 'LYCHEE',
      componentProps: {
        placeholder: '请输入作者名称',
      },
      fieldName: 'authorName',
      label: '作者名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入包名',
      },
      fieldName: 'packageName',
      label: '包名',
      rules: 'required',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: item.itemVal,
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'springboot_models',
        },
        placeholder: '请选择子模块',
        allowClear: true,
      },
      fieldName: 'moduleName',
      label: '子模块',
      help: '代码生成到哪一个子模块',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入模块名',
      },
      fieldName: 'modelNamePrefix',
      label: '模块名',
      help: '如：system',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入前端生成目录名称',
      },
      fieldName: 'frontEndPath',
      label: '前端模块',
      help: '默认在views文件夹下,如：system; 就是views下的system文件夹',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入前端项目路径',
      },
      fieldName: 'frontProjectPath',
      label: '前端项目',
      help: '如果需要生成代码到前端项目中,则需要选择到前端项目根目录',
      rules: 'required',
    },
  ],
});

onMounted(async () => {
  await handleAfreshLoad();
});

async function handleAfreshLoad() {
  const formVals = await genConfigQueryOneApi();
  await otherFormApi.setValues(formVals, false);
  message.success('数据加载成功!');
}

async function onSubmit(values: Record<string, any>) {
  const msg = await genConfigAddOrEditApi(values);
  message.success(msg);
}
</script>

<template>
  <Page auto-content-height>
    <Card title="生成配置">
      <template #extra>
        <Button type="primary" @click="handleAfreshLoad">重新加载数据</Button>
      </template>
      <OtherForm />
    </Card>
  </Page>
</template>
